package com.qd.tc.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qd.base.ResHeader;
import com.qd.dom.XmlUtils;
import com.qd.tc.service.AbstractTCDataConvertService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.qd.http.service.HttpAccessService;
import com.qd.string.StringExUtils;
import com.qd.tc.model.TcGuest;
import com.qd.tc.model.TcSceneryOrder;
import com.qd.tc.model.TcSceneryOrderCancelRes;
import com.qd.tc.model.TcSceneryOrderSubmitRes;
import com.qd.tc.service.TcSceneryOrderService;
import com.qd.util.AccessMethod;

import lombok.Setter;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * @author taomk
 * @version 1.0
 * @since 2014/10/12 23:11
 */
@Slf4j
public class TcSceneryOrderServiceImpl extends AbstractTCDataConvertService implements TcSceneryOrderService {

	@Setter
	private HttpAccessService httpAccessService;

	@Setter
	private String guestParam;

	@Override
	public TcSceneryOrderSubmitRes submit(TcSceneryOrder sceneryOrder) {
		StringBuilder guestParams = new StringBuilder();
        if (CollectionUtils.isNotEmpty(sceneryOrder.getOtherGuestList())){
            for (TcGuest gust : sceneryOrder.getOtherGuestList()) {
                guestParams.append(StringExUtils.replace(guestParam, gust.toMap()));
            }
        }

		sceneryOrder.setOtherGuest(guestParams.toString());
        log.info("调用TC_SCENERY_ORDER_SUBMIT接口，访问参数为：" + sceneryOrder.toMap());
		String res = httpAccessService.access(AccessMethod.TC_SCENERY_ORDER_SUBMIT, sceneryOrder.toMap());
		// TODO res转TcSceneryOrderRes
        log.info("调用TC_SCENERY_ORDER_SUBMIT接口，返回结果为：" + res);
        TcSceneryOrderSubmitRes tcSceneryOrderSubmitRes =  new TcSceneryOrderSubmitRes();
        Document doc = XmlUtils.parseStringToXml(res);
        Element root =  doc.getRootElement();
        //解析header
        ResHeader resHeader = new ResHeader();
        List<Element> headerChildEleList =  root.element("header").elements();
        reflectResultToObj(headerChildEleList, resHeader);
        tcSceneryOrderSubmitRes.setHeader(resHeader);
        //解析body
        if(StringExUtils.isNotNullOrEmpty(resHeader.getRspType()) && resHeader.getRspType().equals("0")){
            Element orderEle =  root.element("body").element("order");//获取order元素列表
            reflectResultToObj(orderEle.elements(), tcSceneryOrderSubmitRes);
        };
        log.info("TcSceneryOrderServiceImpl.submit返回结果为：" + tcSceneryOrderSubmitRes);
		return tcSceneryOrderSubmitRes;
	}

	@Override
	public TcSceneryOrderCancelRes cancel(String serialId, String cancelReason) {
		Map<String, String> param = new HashMap<>();
		param.put("serialId", serialId);
		param.put("cancelReason", cancelReason);
        log.info("调用TC_SCENERY_ORDER_CANCEL接口，访问参数为：" + param);
		String res = httpAccessService.access(AccessMethod.TC_SCENERY_ORDER_CANCEL, param);
        log.info("调用TC_SCENERY_ORDER_CANCEL接口，返回结果为：" + res);
		// TODO res转TcSceneryOrderCancelRes
        TcSceneryOrderCancelRes tcSceneryOrderCancelRes = new TcSceneryOrderCancelRes();
        Document doc = XmlUtils.parseStringToXml(res);
        Element root =  doc.getRootElement();
        //解析header
        ResHeader resHeader = new ResHeader();
        List<Element> headerChildEleList =  root.element("header").elements();
        reflectResultToObj(headerChildEleList, resHeader);
        tcSceneryOrderCancelRes.setHeader(resHeader);
        //解析body
        if(StringExUtils.isNotNullOrEmpty(resHeader.getRspType()) && (
                resHeader.getRspType().equals("0") || resHeader.getRspType().equals("2")
                )){
            List<Element> bodyChildEleList =  root.element("body").elements();//获取scenery元素列表
            reflectResultToObj(bodyChildEleList, tcSceneryOrderCancelRes);
        }
        log.info("TcSceneryOrderServiceImpl.cancel返回结果为：" + tcSceneryOrderCancelRes);
		return tcSceneryOrderCancelRes;
	}

	@Override
	public Map<String, String> findOrderStatus(String... serialIds) {
		Map<String, String> result = new HashMap<>();

		StringBuilder serialIdParam = new StringBuilder();
		int count = 1;
		for (String serialId : serialIds) {
			if (count % 20 == 0) {
				result.putAll(findOrderStatusBySerialIds(serialIdParam.toString()));
				serialIdParam = new StringBuilder();
			}
			serialIdParam.append(serialId).append(",");
			count++;
		}

		if (StringUtils.isNotBlank(serialIdParam.toString())) {
			result.putAll(findOrderStatusBySerialIds(serialIdParam.toString()));
		}
		return result;
	}

	private Map<String, String> findOrderStatusBySerialIds(String serialIds) {
		Map<String, String> param = new HashMap<>();
		param.put("serialIds", serialIds);
		param.put("writeDB", "0");
        log.info("调用TC_SCENERY_ORDER_DETAILL接口，访问参数为：" + param);
		String res = httpAccessService.access(AccessMethod.TC_SCENERY_ORDER_DETAIL, param);
        log.info("调用TC_SCENERY_ORDER_DETAILL接口，返回结果为：" + res);
		// TODO 从res中解析出每个订单的支付状态
        Map<String, String> resultMap = new HashMap();
        Document doc = XmlUtils.parseStringToXml(res);
        Element root =  doc.getRootElement();
        //解析header
        ResHeader resHeader = new ResHeader();
        List<Element> headerChildEleList =  root.element("header").elements();
        reflectResultToObj(headerChildEleList, resHeader);
        //解析body
        if(StringExUtils.isNotNullOrEmpty(resHeader.getRspType()) && resHeader.getRspType().equals("0")){
            Element orderListEle =  root.element("body").element("orderList");//获取orderList元素
            if(orderListEle != null){
                List<Element> orderEleList = orderListEle.elements();
                for (Element orderChildEle : orderEleList){
                    Map<String, String> orderMap = new HashMap();
                    orderMap.put("serialId", "");
                    orderMap.put("orderStatus", "");
                    reflectResultToMap(orderChildEle.elements(), orderMap);
                    resultMap.put(orderMap.get("serialId"), orderMap.get("orderStatus"));
                }
            }
        }
        log.info("TcSceneryOrderServiceImpl.findOrderStatusBySerialIds返回结果为：" + resultMap);
		return resultMap;
	}
}
